package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.adapter.NewExpCycleStageAdapter;
import com.snap.vseries.adapter.NewExpLightingAdapter;
import com.snap.vseries.adapter.NewExpProgramAdapter;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.base.OnItemClickListener;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.ProgramRecycle;
import com.snap.vseries.bean.ProgramSection;
import com.snap.vseries.bean.ProgramStage;
import com.snap.vseries.ui.ExpNewExperimentActivity;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.ui.widget.ReSpinner;
import com.snap.vseries.ui.widget.TextButton;
import com.snap.vseries.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.AutoSizeUtils;

@SuppressLint("ValidFragment")
public class NewExperimentProgramSettingFragment extends BaseFragment {
    @BindView(R.id.device_rv)
    RecyclerView programRv;
    @BindView(R.id.cycle_stage_rv)
    RecyclerView cycleStageRv;
    @BindView(R.id.lighting_rv)
    RecyclerView lightingRv;
    @BindView(R.id.add_section_btn)
    TextButton addStageBtn;
    @BindView(R.id.add_recycle_stage_btn)
    TextButton setRecycleBtn;
    @BindView(R.id.btn_melting_curve)
    SwitchCompat btnMeltingCurve;
    @BindView(R.id.btn_start)
    TextButton btnStart;
    @BindView(R.id.btn_end)
    TextButton btnEnd;
    @BindView(R.id.sp_level)
    ReSpinner spLevel;
    @BindView(R.id.recycle_stage_title_ll)
    LinearLayout recycleStageTitleLl;
    private ExpInfo expInfo;

    /**
     * 所有段信息
     */
    private List<ProgramStage> programStages;
    /**
     * 所有的节信息
     */
    private List<ProgramSection> sections;
    /**
     * 循环段
     */
    private ArrayList<ProgramRecycle> recycleStages;
    /**
     * 实验程序
     */
    private NewExpProgramAdapter programAdapter;
    /**
     * 设定循环，设定循环阶段，把节组装为段；
     * 数据源： List<ProgramRecycle> recycleStages
     * ProgramRecycle：段（包含段起始节，以及循环信息）
     */
    private NewExpCycleStageAdapter cycleAdapter;
    /**
     * 数据采集，是否采光
     * 每增加一个循环段，就增加相对应的段内节的采光开关
     */
    private NewExpLightingAdapter lightAdapter;


    @SuppressLint("ValidFragment")
    public NewExperimentProgramSettingFragment(ExpInfo expInfo) {
        this.expInfo = expInfo;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_new_experiment_program_setting;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setIndex();
        initViews();
    }


    @OnClick({R.id.add_section_btn, R.id.add_recycle_stage_btn, R.id.btn_next, R.id.btn_start, R.id.btn_end})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.add_section_btn:
                addSection();
                break;
            case R.id.add_recycle_stage_btn:
                //设定循环，添加段
                recycleStages.add(new ProgramRecycle(-1, -1, 40, false));
                cycleAdapter.notifyItemChangedLast(recycleStages);

                lightAdapter.updateData(recycleStages);
                break;
            case R.id.btn_next:
                //自定义设置模式下才需要勾选
                boolean hasRecycle = false;
                for (ProgramRecycle recycle : recycleStages) {
                    if (recycle.getStartIndex() != -1 && recycle.getEndIndex() != -1) {
                        hasRecycle = true;
                        break;
                    }
                }
                if (!hasRecycle) {
                    ToastUtils.get().showText("循环段不能为空");
                    return;
                }
                makeProgram();
                ExpNewExperimentActivity activity = (ExpNewExperimentActivity) getActivity();
                Objects.requireNonNull(activity).showFragment(activity.index + 1);
                break;
            case R.id.btn_start:
                startSetting();
                break;
            case R.id.btn_end:
                endSetting();
                break;
            default:
                break;
        }
    }

    private void initViews() {
        initData();
        initSetting();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setIndex();
            initViews();
        }
    }

    private void setIndex() {
        ExpNewExperimentActivity activity = (ExpNewExperimentActivity) getActivity();
        Objects.requireNonNull(activity).index = 2;
    }

    private void initData() {
        if (recycleStages == null || sections == null || expInfo.getProgram() == null) {
            recycleStages = new ArrayList<>();
            programStages = new ArrayList<>();
            sections = new ArrayList<>();
            sections.add(new ProgramSection(120, 50f, 1));
            sections.add(new ProgramSection(20, 95f, 2));
            sections.add(new ProgramSection(10, 95f, 3));
            sections.add(new ProgramSection(20, 55f, 4));
        }
    }

    private void initSetting() {
        //实验程序
        programRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        programAdapter = new NewExpProgramAdapter(getContext(), sections, getFragmentManager());
        programRv.setAdapter(programAdapter);
        programAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                sections.remove(sections.get(position));
                for (int i = 0; i < sections.size(); i++) {
                    sections.get(i).setSectionIndex(i + 1);
                }
                // 只要执行删除节，就清空循环段
                programAdapter.updateData(sections);
                removeRecycleStage();
                updateCycleAdapter();
                lightAdapter.updateData(recycleStages);
            }
        });
        //设定循环
        cycleAdapter = new NewExpCycleStageAdapter(getContext(), recycleStages, sections.size());
        cycleStageRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        cycleStageRv.setAdapter(cycleAdapter);

        cycleAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                //循环段设置成功，更新采光列表
                lightAdapter.notifyDataSetChanged();
            }
        });
        cycleAdapter.setOnItemDeleteClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                updateCycleAdapter();
            }
        });
        //数据采集
        lightAdapter = new NewExpLightingAdapter(getContext(), recycleStages);
        lightingRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        lightingRv.setAdapter(lightAdapter);


        // TODO: 2020/9/16 溶解曲线开关
        btnMeltingCurve.setChecked(expInfo.isAnalyzed());
        btnMeltingCurve.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                expInfo.setAnalyzed(isChecked);
            }
        });

        showSpinner();
    }

    private void updateCycleAdapter() {
        recycleStageTitleLl.setVisibility(recycleStages.size() == 0 ? View.GONE : View.VISIBLE);
        cycleAdapter.updateData(recycleStages, sections.size());
    }

    public void startSetting() {
        new DialogView(getContext())
                .setTitle("修改运行次数")
                .setHint("请输入运行次数")
                .setContentNumberType()
                .setOnClickListener(content -> {
                    if (content.isEmpty()) {
                        ToastUtils.get().showText("运行次数不允许为空");
                        return;
                    }
                    btnStart.setText(content + " ℃");
                })
                .show();
    }

    public void endSetting() {
        new DialogView(getContext())
                .setTitle("修改运行次数")
                .setHint("请输入运行次数")
                .setContentNumberType()
                .setOnClickListener(content -> {
                    if (content.isEmpty()) {
                        ToastUtils.get().showText("运行次数不允许为空");
                        return;
                    }
                    btnEnd.setText(content + " ℃");
                })
                .show();
    }

    private void showSpinner() {
        List<String> startList = new ArrayList<>();
        startList.add("0.02  ℃/s");
        startList.add("0.1  ℃/s");
        startList.add("0.5  ℃/s");
        ArrayAdapter<String> startAdapter = new ArrayAdapter<>(mContext, R.layout.spinner_layout, startList);
        spLevel.setAdapter(startAdapter);
        //设置选中之后的监听
        spLevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                TextView tv = (TextView) view;
                if (tv == null) {
                    return;
                }
                tv.setTextColor(0xFF568BFF);
                tv.setTextSize(14);
                tv.setPadding(AutoSizeUtils.dp2px(getContext(), 16), 0, 0, 0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    /**
     * sections->programStages的转化过程：节正序排列，根据recycleStages（循环段信息)构成段
     * sections:所有的节
     * programStages：所有的段，其中包括循环段和单次段
     * recycleStages:循环段信息
     */
    private void makeProgram() {
        programStages.clear();
        sortRecycleStages();
        //节序从1开始
        int startIndex = 1;
        for (ProgramRecycle recycle : recycleStages) {
            if (recycle.getStartIndex() == -1 || recycle.getEndIndex() == -1) {
                continue;
            }
            //将每个循环段前面的，不包含在循环段中的节（即循环次数为1的节），单独成段
            for (int i = startIndex; i < recycle.getStartIndex(); i++) {
                ProgramStage singleCycleStage = new ProgramStage();
                sections.get(i - 1).setCycleCount(1);
                sections.get(i - 1).setLighting(false);
                singleCycleStage.addSection(sections.get(i - 1));
                programStages.add(singleCycleStage);
            }
            //添加循环段（组装节）
            ProgramStage stage = new ProgramStage();
            List<ProgramSection> sectionList = new ArrayList<>();
            for (int j = recycle.getStartIndex(); j <= recycle.getEndIndex(); j++) {
                sections.get(j - 1).setLighting(recycle.isLighting() && recycle.getLightingIndex() == j);
                sections.get(j - 1).setCycleCount(recycle.getCycleCount());
                sectionList.add(sections.get(j - 1));
            }
            stage.setCycleCount(recycle.getCycleCount());
            stage.setSections(sectionList);
            programStages.add(stage);
            startIndex = recycle.getEndIndex() + 1;
        }
        //如果有循环数为1的节在后面，最后也要插入进去
        int endIndex = 0;
        if (recycleStages.size() > 0) {
            endIndex = recycleStages.get(recycleStages.size() - 1).getEndIndex();
        }

        if (endIndex < sections.size()) {
            for (int i = endIndex; i < sections.size(); i++) {
                ProgramStage singleCycleStage = new ProgramStage();
                sections.get(i).setLighting(false);
                singleCycleStage.addSection(sections.get(i));
                programStages.add(singleCycleStage);
            }
        }
        expInfo.setProgram(programStages);
    }

    private void sortRecycleStages() {
        Collections.sort(recycleStages, (o1, o2) -> o1.getStartIndex() - o2.getStartIndex());
    }


    /**
     * 点击添加一个节
     */
    private void addSection() {
        sections.add(new ProgramSection(10, 95f, sections.size() + 1));
        programAdapter.updateData(sections);
        updateCycleAdapter();
    }

    private void removeRecycleStage() {
        recycleStages.clear();
        for (int i = 0; i < sections.size(); i++) {
            sections.get(i).setCycleCount(1);
        }
    }
}
